<template>
  <div class="order-pay">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>订单支付</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="container" v-loading="loading">
      <div class="pay-content" v-if="orderDetail">
        <!-- 订单信息 -->
        <div class="order-info-section">
          <h3>订单信息</h3>
          <div class="order-summary">
            <div class="order-header">
              <div class="order-no">
                <span class="label">订单号：</span>
                <span class="value">{{ orderDetail.orderNo }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(orderDetail.orderStatus)">
                  {{ getStatusText(orderDetail.orderStatus) }}
                </el-tag>
              </div>
            </div>
            
            <div class="order-goods">
              <div v-for="item in orderDetail.items" :key="item.id" class="goods-item">
                <div class="goods-image">
                  <img :src="item.productImage || '/placeholder.svg'" :alt="item.productName" />
                </div>
                <div class="goods-info">
                  <h4>{{ item.productName }}</h4>
                  <p v-if="item.skuSpecifications" class="goods-spec">
                    {{ formatSpecifications(item.skuSpecifications) }}
                  </p>
                  <div class="goods-price">
                    <span class="price">¥{{ item.price }}</span>
                    <span class="quantity">x{{ item.quantity }}</span>
                  </div>
                </div>
                <div class="goods-total">
                  ¥{{ item.totalAmount }}
                </div>
              </div>
            </div>

            <div class="order-amount">
              <div class="amount-item">
                <span>商品总价</span>
                <span>¥{{ orderDetail.goodsAmount }}</span>
              </div>
              <div class="amount-item">
                <span>运费</span>
                <span>¥{{ orderDetail.shippingFee }}</span>
              </div>
              <div class="amount-item" v-if="orderDetail.pointsAmount > 0">
                <span>积分抵扣</span>
                <span class="discount">-¥{{ orderDetail.pointsAmount }}</span>
              </div>
              <div class="amount-item total">
                <span>应付金额</span>
                <span class="total-price">¥{{ orderDetail.totalAmount }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="payment-section" v-if="orderDetail.orderStatus === OrderStatus.PENDING_PAYMENT">
          <h3>选择支付方式</h3>
          <div class="payment-methods">
            <div 
              v-for="method in paymentMethods" 
              :key="method.value"
              class="payment-method"
              :class="{ active: selectedPaymentMethod === method.value }"
              @click="selectedPaymentMethod = method.value"
            >
              <div class="method-icon">
                <i :class="method.icon"></i>
              </div>
              <div class="method-info">
                <div class="method-name">{{ method.name }}</div>
                <div class="method-desc">{{ method.description }}</div>
              </div>
              <div class="method-radio">
                <el-radio :label="method.value" v-model="selectedPaymentMethod" />
              </div>
            </div>
          </div>
        </div>

        <!-- 支付密码输入（模拟） -->
        <div class="password-section" v-if="showPasswordInput">
          <h3>输入支付密码</h3>
          <div class="password-input">
            <el-input
              v-model="paymentPassword"
              type="password"
              placeholder="请输入6位支付密码"
              maxlength="6"
              show-password
              @input="handlePasswordInput"
            />
            <p class="password-tip">模拟支付，请输入任意6位数字作为支付密码</p>
          </div>
        </div>

        <!-- 支付结果 -->
        <div class="payment-result" v-if="paymentResult">
          <div class="result-content" :class="paymentResult.success ? 'success' : 'failed'">
            <div class="result-icon">
              <i :class="paymentResult.success ? 'el-icon-success' : 'el-icon-error'"></i>
            </div>
            <div class="result-text">
              <h3>{{ paymentResult.title }}</h3>
              <p>{{ paymentResult.message }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="pay-footer" v-if="orderDetail && orderDetail.orderStatus === OrderStatus.PENDING_PAYMENT && !paymentResult">
        <div class="footer-content">
          <div class="amount-info">
            <span class="amount-text">应付金额：</span>
            <span class="amount-price">¥{{ orderDetail.totalAmount }}</span>
          </div>
          <div class="footer-actions">
            <el-button size="large" @click="cancelOrder" :loading="cancelling">
              取消订单
            </el-button>
            <el-button 
              type="primary" 
              size="large" 
              @click="handlePayment" 
              :loading="paying"
              :disabled="!selectedPaymentMethod"
            >
              {{ showPasswordInput ? '确认支付' : '立即支付' }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 支付成功后的操作 -->
      <div class="success-footer" v-if="paymentResult && paymentResult.success">
        <div class="footer-content">
          <div class="footer-actions">
            <el-button size="large" @click="goToOrders">查看订单</el-button>
            <el-button type="primary" size="large" @click="goToHome">继续购物</el-button>
          </div>
        </div>
      </div>

      <!-- 订单不存在 -->
      <div class="no-order" v-if="!loading && !orderDetail">
        <el-empty description="订单不存在或已被删除">
          <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useOrderStore } from '@/stores/order'
import { PaymentMethod, OrderStatus } from '@/api/order'

const router = useRouter()
const route = useRoute()
const orderStore = useOrderStore()

// 响应式数据
const loading = ref(false)
const paying = ref(false)
const cancelling = ref(false)
const selectedPaymentMethod = ref<PaymentMethod>(PaymentMethod.ALIPAY)
const showPasswordInput = ref(false)
const paymentPassword = ref('')
const paymentResult = ref<{
  success: boolean
  title: string
  message: string
} | null>(null)

// 支付方式配置
const paymentMethods = [
  {
    value: PaymentMethod.ALIPAY,
    name: '支付宝',
    description: '推荐使用支付宝，安全快捷',
    icon: 'el-icon-wallet'
  },
  {
    value: PaymentMethod.WECHAT,
    name: '微信支付',
    description: '微信安全支付',
    icon: 'el-icon-chat-dot-round'
  },
  {
    value: PaymentMethod.BANK_CARD,
    name: '银行卡',
    description: '储蓄卡、信用卡均可',
    icon: 'el-icon-credit-card'
  }
]

// 计算属性
const orderDetail = computed(() => orderStore.currentOrder)

// 方法
const formatSpecifications = (specs: any) => {
  if (!specs || typeof specs !== 'object') return ''
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ')
}

const getStatusType = (status: OrderStatus) => {
  const statusMap = {
    [OrderStatus.PENDING_PAYMENT]: 'warning',
    [OrderStatus.PENDING_SHIPMENT]: 'success',
    [OrderStatus.PENDING_RECEIPT]: 'info',
    [OrderStatus.COMPLETED]: 'success',
    [OrderStatus.CANCELLED]: 'danger',
    [OrderStatus.REFUNDING]: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: OrderStatus) => {
  const statusMap = {
    [OrderStatus.PENDING_PAYMENT]: '待支付',
    [OrderStatus.PENDING_SHIPMENT]: '待发货',
    [OrderStatus.PENDING_RECEIPT]: '待收货',
    [OrderStatus.COMPLETED]: '已完成',
    [OrderStatus.CANCELLED]: '已取消',
    [OrderStatus.REFUNDING]: '退款中'
  }
  return statusMap[status] || '未知状态'
}

const handlePasswordInput = (value: string) => {
  // 只允许输入数字
  paymentPassword.value = value.replace(/\D/g, '')
}

const handlePayment = async () => {
  if (!orderDetail.value) return

  if (!showPasswordInput.value) {
    // 第一步：显示密码输入
    showPasswordInput.value = true
    return
  }

  // 第二步：验证密码并支付
  if (paymentPassword.value.length !== 6) {
    ElMessage.error('请输入6位支付密码')
    return
  }

  try {
    paying.value = true

    // 模拟支付处理延迟（1-3秒）
    const delay = Math.random() * 2000 + 1000
    await new Promise(resolve => setTimeout(resolve, delay))

    // 模拟支付结果（95%成功率，更真实的体验）
    const isSuccess = Math.random() > 0.05

    if (isSuccess) {
      // 调用支付接口
      const result = await orderStore.payOrder(orderDetail.value.id, selectedPaymentMethod.value)
      
      if (result) {
        paymentResult.value = {
          success: true,
          title: '支付成功',
          message: `订单 ${orderDetail.value.orderNo} 支付成功！\n订单状态已更新为待发货，我们将尽快为您安排发货。`
        }

        ElMessage.success('支付成功！订单状态已更新')
        
        // 刷新订单详情以获取最新状态
        await fetchOrderDetail()
      } else {
        throw new Error('支付接口调用失败')
      }
    } else {
      paymentResult.value = {
        success: false,
        title: '支付失败',
        message: '支付过程中出现问题，请重试或选择其他支付方式。\n如果多次失败，请联系客服。'
      }

      ElMessage.error('支付失败，请重试')
    }
  } catch (error) {
    console.error('支付失败:', error)
    paymentResult.value = {
      success: false,
      title: '支付失败',
      message: '网络异常或系统繁忙，请检查网络连接后重试。\n如果问题持续存在，请联系客服。'
    }
    ElMessage.error('支付失败，请稍后重试')
  } finally {
    paying.value = false
  }
}

const cancelOrder = async () => {
  if (!orderDetail.value) return

  try {
    await ElMessageBox.confirm('确认取消订单？取消后无法恢复', '提示', {
      confirmButtonText: '确认取消',
      cancelButtonText: '继续支付',
      type: 'warning'
    })

    cancelling.value = true
    await orderStore.cancelOrder(orderDetail.value.id)
    
    ElMessage.success('订单已取消')
    router.push('/orders')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  } finally {
    cancelling.value = false
  }
}

const goToOrders = () => {
  router.push('/orders')
}

const goToHome = () => {
  router.push('/')
}

const fetchOrderDetail = async () => {
  const orderId = route.params.orderId as string
  if (!orderId) {
    ElMessage.error('订单ID不存在')
    router.push('/')
    return
  }

  try {
    loading.value = true
    await orderStore.getOrderById(parseInt(orderId))
    
    if (!orderDetail.value) {
      ElMessage.error('订单不存在')
      router.push('/')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
    router.push('/')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-pay {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100px;
}

.breadcrumb {
  background: white;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.pay-content {
  margin: 20px 0;
}

.order-info-section,
.payment-section,
.password-section,
.payment-result {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-info-section h3,
.payment-section h3,
.password-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #ff6900;
  padding-bottom: 10px;
}

/* 订单信息 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.order-no .label {
  color: #666;
}

.order-no .value {
  font-weight: 600;
  color: #333;
}

/* 商品列表 */
.order-goods {
  margin-bottom: 20px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 60px;
  height: 60px;
  margin-right: 15px;
  border-radius: 6px;
  overflow: hidden;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  flex: 1;
}

.goods-info h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.goods-spec {
  margin: 0 0 5px 0;
  font-size: 12px;
  color: #666;
}

.goods-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

.goods-price .price {
  font-size: 14px;
  font-weight: 600;
  color: #ff6900;
}

.goods-price .quantity {
  font-size: 12px;
  color: #666;
}

.goods-total {
  font-size: 16px;
  font-weight: 600;
  color: #ff6900;
}

/* 金额明细 */
.order-amount {
  border-top: 1px solid #e0e0e0;
  padding-top: 15px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.amount-item.total {
  font-weight: 600;
  font-size: 16px;
  border-top: 1px solid #e0e0e0;
  padding-top: 15px;
  margin-top: 10px;
}

.amount-item .discount {
  color: #67c23a;
}

.amount-item .total-price {
  color: #ff6900;
  font-size: 18px;
}

/* 支付方式 */
.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-method:hover {
  border-color: #ff6900;
}

.payment-method.active {
  border-color: #ff6900;
  background: #fff7f0;
}

.method-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  background: #f5f5f5;
  border-radius: 50%;
}

.method-icon i {
  font-size: 20px;
  color: #666;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.method-desc {
  font-size: 14px;
  color: #666;
}

/* 支付密码 */
.password-input {
  max-width: 300px;
}

.password-tip {
  margin: 10px 0 0 0;
  font-size: 12px;
  color: #666;
}

/* 支付结果 */
.payment-result {
  text-align: center;
}

.result-content {
  padding: 40px 20px;
}

.result-icon {
  margin-bottom: 20px;
}

.result-icon i {
  font-size: 60px;
}

.result-content.success .result-icon i {
  color: #67c23a;
}

.result-content.failed .result-icon i {
  color: #f56c6c;
}

.result-text h3 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 600;
}

.result-content.success .result-text h3 {
  color: #67c23a;
}

.result-content.failed .result-text h3 {
  color: #f56c6c;
}

.result-text p {
  margin: 0;
  font-size: 16px;
  color: #666;
}

/* 底部操作栏 */
.pay-footer,
.success-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #e0e0e0;
  padding: 15px 0;
  z-index: 100;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.amount-text {
  font-size: 16px;
  color: #333;
}

.amount-price {
  font-size: 24px;
  font-weight: 600;
  color: #ff6900;
}

.footer-actions {
  display: flex;
  gap: 15px;
}

.success-footer .footer-content {
  justify-content: center;
}

/* 空状态 */
.no-order {
  background: white;
  padding: 60px 20px;
  margin: 20px 0;
  border-radius: 8px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .goods-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .goods-image {
    align-self: center;
  }
  
  .goods-total {
    align-self: flex-end;
  }
  
  .footer-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .footer-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>